package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException, ClassNotFoundException {
        Document docment = new SAXReader().read(in);

        Element rootElement = docment.getRootElement();

        parseElementTag(rootElement,"select");

        parseElementTag(rootElement,"insert");

        parseElementTag(rootElement,"update");

        parseElementTag(rootElement,"delete");

    }

    /**
     * 解析mapper文件中的标签 insert update delete select
     * @param rootElement
     * @param tagName
     * @throws ClassNotFoundException
     */
    private void parseElementTag(Element rootElement,String tagName ) throws ClassNotFoundException {
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//"+tagName);
        for (Element element : list) {
            String id = element.attributeValue("id");
            Class<?> resultType = getClassType(element.attributeValue("resultType"));
            Class<?> parameterType = getClassType(element.attributeValue("parameterType"));
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setTagType(tagName);

            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key ,mappedStatement);
        }
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if(parameterType==null) return null;
        return Class.forName(parameterType);
    }
}
